import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_detail_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_add_admin_bar_widget.dart';
import 'package:e_reception_flutter/ui/company/manager/select_person_page.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/widgets/create_user_edit_widget.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../../common_person_list_item_widget.dart';
import '../../common_person_list_response.dart';
import 'add_or_edit_department_page.dart';
import 'class_or_department_admin_detail.dart';
import 'class_or_department_viewmodel.dart';
import 'dart:math' as Math;

import 'event/admin_change_event.dart';
import 'member/add_member_page.dart';

///班级或部门详情
class ClassOrDepartmentDetail extends StatefulWidget {
  static const String ROUTER = 'ClassOrDepartmentDetail';
  final DepartmentOrClassListItemBean oldBean;
  final int type;

  const ClassOrDepartmentDetail({Key key, this.oldBean, this.type})
      : super(key: key);

  ///跳转方法
  static Future<DepartmentOrClassListItemBean> navigatorPush(
      BuildContext context, DepartmentOrClassListItemBean oldBean, int type) {
    return RouterUtils.routeForFutureResult<DepartmentOrClassListItemBean>(
      context,
      ClassOrDepartmentDetail(
        oldBean: oldBean,
        type: type,
      ),
      routeName: ClassOrDepartmentDetail.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return ClassOrDepartmentDetailState();
  }
}

class ClassOrDepartmentDetailState extends BaseState<ClassOrDepartmentDetail> {
  bool isLoading = true;
  bool isError = false;

  ClassOrDepartmentViewModel _viewModel;

  ///管理员列表
  List<CommonPersonBean> adminList = List();

  ///成员学员列表
  List<CommonPersonBean> memberList = List();

  ///是否显示全部管理员
  ValueNotifier<bool> showAllAdminValueNotifier;

  @override
  void initState() {
    _viewModel = ClassOrDepartmentViewModel(this);
    super.initState();
    showAllAdminValueNotifier = ValueNotifier(null);
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is AdminChangeEvent || event is CompanyNumBarEventMonitor) {
        print('ClassOrDepartmentDetailState' + event.toString());
        _viewModel.getDetail(widget.oldBean.getId());
      }
    });
    _viewModel.detailValueStream.listen((AdminMemberListBean result) {
      isLoading = false;
      loading(false);
      if (result == null) {
        isError = true;
      } else {
        adminList.clear();
        memberList.clear();
        if (result.adminList != null) {
          adminList.addAll(result.adminList);
        }
        if (adminList.length > 2) {
          showAllAdminValueNotifier.value = false;
        } else {
          showAllAdminValueNotifier.value = true;
        }
        if (result.memberList != null) {
          memberList.addAll(result.memberList);
        }
      }

      setState(() {
        widget.oldBean.adminCnt = adminList.length;
        widget.oldBean.memberCnt = memberList.length;
      });
    });
    _viewModel.getDetail(widget.oldBean.getId());
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: <Widget>[
            VgTopBarWidget(
                centerWidget: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Spacer(),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: _toEditPage(),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxWidth: 230),
                        child: Container(
                          margin: EdgeInsets.only(left: 10),
                          child: Text(VgStringUtils.subStringAndAppendSymbol(
                              widget?.oldBean?.getName(), 15,
                              symbol: "...") ?? '',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: 17,
                                height: 1.2,
                                color: ThemeRepository.getInstance()
                                    .getTextMainColor_D0E0F7()),
                          ),
                        ),
                      ),
                    ), GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: _toEditPage(),
                      child: Visibility(
                        visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
                        child:Opacity(
                          opacity: AppOverallDistinguish.comefromAiOrWeStudy() || widget.type == 0 ?1 :0,
                          child: Container(
                              margin: EdgeInsets.only(left: 4,bottom: 15,top: 15,right: 10),
                              alignment: Alignment.centerLeft,
                              width: 11,
                              height: 12,
                              child: Image.asset('images/icon_edit.png')),
                        ),
                      ),
                    ),
                    Spacer(),
                  ],
                ),
                isShowBack: true,
                rightPadding: 40),
            Expanded(
              child: VgPlaceHolderStatusWidget(
                loadingStatus: isLoading,
                errorStatus: isError,
                child: Column(
                  children: <Widget>[
                    // _adminNumAddBar(),
                    _memberNumAddBar(),
                    Expanded(
                      child: //成员列表
                          _memberListWidget(),
                    ),
                    _adminBar()
                  ],
                ),
              ),
            )
          ],
        ),
      ),
      navigationBarColor: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///成员列表
  _memberListWidget() {
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemBuilder: (context, index) {
          return _listItem(memberList[index]);
        },
        itemCount: memberList.length,
      ),
    );
  }

  ///管理员列表
  Widget _adminList() {
//3、管理员大于2要折叠
//4、上滑的时候，管理员和成员的一张在顶部悬停
    return ValueListenableBuilder(
      valueListenable: showAllAdminValueNotifier,
      builder: (BuildContext context, bool value, Widget child) {
        int showCount = adminList.length;
        bool showAllTip = false;
        if (showCount > 2) {
          if (showAllAdminValueNotifier.value) {
            showCount = adminList.length;
            showAllTip = false;
          } else {
            showCount = 2;
            showAllTip = true;
          }
        } else {
          showAllTip = false;
        }
        return Column(
          children: <Widget>[
            ListView.builder(
              padding: EdgeInsets.zero,
              itemBuilder: (context, index) {
                return _listItem(adminList[index]);
              },
              itemCount: showCount,
              shrinkWrap: true,
            ),
            Visibility(
              visible: showAllTip,
              child: GestureDetector(
                onTap: () {
                  showAllAdminValueNotifier.value = true;
                },
                child: Container(
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  height: 45,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        '展开全部',
                        style: TextStyle(
                            color: ThemeRepository.getInstance()
                                .getDefaultGrayColor_FF5E687C(),
                            fontSize: 12),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 3.0, left: 4),
                        child: Image.asset(
                          'images/icon_show_more.png',
                          width: 8,
                          height: 7,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )
          ],
        );
      },
    );
  }

  Widget _listItem(CommonPersonBean data) {
    return GestureDetector(
      onTap: () {
        PersonDetailPage.navigatorPush(context, data.fuid, fid:data.fid, pages: ClassOrDepartmentDetail.ROUTER);
      },
      onLongPress: (){
        _pushMoreMenuDialog(data?.name, data?.fuid, data?.roleid, data?.userid);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        child: _toMainRowWidget(data),
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
      ),
    );
  }

  ///弹出更多菜单弹窗
  void _pushMoreMenuDialog(String name, String fuid, String roleid, String userid) {
    CommonMoreMenuDialog.navigatorPushDialog(context, {
      "删除":()async{
        bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定删除"+"${name??"该用户"}？删除后不可恢复",
            cancelText: "取消",
            confirmText: "删除",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355());
        if (result ?? false) {
          _viewModel?.deleteUser(context,
              fuid: fuid,
              roleid: roleid,
              userid: userid,);
        }
      }
    });
  }

  Widget _toMainRowWidget(CommonPersonBean data) {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(data.putpicurl) ??
                  showOriginEmptyStr(data.napicurl ?? "") ??
                  '',
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              data.department?.trim(),
              data.projectname?.trim(),
              data.city?.trim(),
              data.classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              //姓名
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  CommonNameAndNickWidget(
                    name: data.name,
                    nick: data.nick,
                  ),
                  VgLabelUtils.getRoleLabel(data.roleid) ?? Container(),
                  _toPhoneWidget(data),
                ],
              ),
              SizedBox(
                height: 3,
              ),
              _toColumnWidget(data)
            ],
          ),
        ),
        Spacer(),
        Image.asset(
          "images/go_ico.png",
          width: 6,
          color: VgColors.INPUT_BG_COLOR,
        )
      ],
    );
  }

  Widget _toPhoneWidget(CommonPersonBean data) {
    return Offstage(
      offstage: data.phone == null || data.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(data.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  /// 李珊珊添加·未激活 /打卡时间
  /// 分类名称·编号
  _toColumnWidget(CommonPersonBean data) {
    return DefaultTextStyle(
      style: TextStyle(height: 1.2),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          //未激活的
          UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()?
          (data.isAlive() ?? true)
              ? _faceTime(data)
              : Text.rich(TextSpan(children: [
                  TextSpan(
                      text: StringUtils.isEmpty(data.uname)
                          ? ''
                          : '${data.uname}添加·',
                      style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
                  TextSpan(
                      text: '未激活',
                      style: TextStyle(fontSize: 12, color: Color(0xfff95355)))
                ]))
              :
          Text(
              '${data.uname??""}添加',
              style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
          //激活的显示上次打卡时间,
        ],
      ),
    );
  }

  ///成员
  _memberNumAddBar() {
    return ValueListenableBuilder(
      valueListenable: _viewModel.todayFaceCnt,
      builder: (context,faceCnt, child) {

       return TitleNumberAndAddBtnBarWidget(
          widget.oldBean.isClass() ? '学员' : '成员', widget.oldBean.memberCnt,
              () async {
            bool result = await AddMemberPage.navigatorPush(context, widget.oldBean);
            if (result != null && result) {
              loading(true);
              _viewModel.getDetail(widget.oldBean.getId());
            }
          },secondWidget: _todayFaceCnt(faceCnt),type:widget.type);
      },
    );
  }

  ///去编辑页面
  _toEditPage() {
    return () async {
      if(!VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())){
        return;
      }
      //编辑部门/班级
      DepartmentOrClassListItemBean result =
          await AddOrEditClassDepartmentPage.navigatorPush(
              context, widget.type, true,
              oldBean: widget.oldBean);
      if (result != null) {
        //列表更新数据
        widget.oldBean.setName(result.getName());
        setState(() {});
        loading(true);
        _viewModel.getDetail(widget.oldBean.getId());
      }
    };
  }

  ///管理员条
  _adminBar() {
    return GestureDetector(
      onTap: () {
        ClassOrDepartmentAdminDetail.navigatorPush(
            context, widget.oldBean, widget.type,
            adminList: adminList);
      },
      child: Container(
          height: 50,
          padding: EdgeInsets.symmetric(horizontal: 15),
          color: ThemeRepository.getInstance().getLineColor_3A3F50(),
          width: double.infinity,
          child: Row(
            children: <Widget>[
              Text(
                "管理员·${widget.oldBean.adminCnt ?? 0}人",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC(),
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    height: 1.2),
              ),
              Expanded(
                child: Container(
                  height: 28,
                  alignment: Alignment.centerRight,
                  child: ListView.separated(
                    padding: EdgeInsets.zero,
                    scrollDirection: Axis.horizontal,
                    reverse: true,
                    itemBuilder: (context, index) {
                      return _adminAvatars(adminList[index]);
                    },
                    separatorBuilder: (context, index) {
                      return SizedBox(width: 6);
                    },
                    itemCount: adminList.length > 3 ? 3 : adminList.length,
                  ),
                ),
              ),
              SizedBox(width: 9),
              Image.asset(
                "images/go_ico.png",
                width: 6,
                color: VgColors.INPUT_BG_COLOR,
              )
            ],
          )),
    );
  }

  _adminAvatars(CommonPersonBean bean) {
    return Container(
      width: 28,
      height: 28,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(28),
        child: Container(
          width: 28,
          height: 28,
          child: VgCacheNetWorkImage(
            showOriginEmptyStr(bean?.putpicurl) ??
                showOriginEmptyStr(bean?.napicurl ?? "") ??
                '',
            fit: BoxFit.cover,
            imageQualityType: ImageQualityType.middleDown,
            defaultErrorType: ImageErrorType.head,
            defaultPlaceType: ImagePlaceType.head,
          ),
        ),
      ),
    );
  }

  ///刷脸时间
  _faceTime(CommonPersonBean itemBean) {
    //今天10：00 至 19：00  20小时
    final bool isShowMax =
        VgToolUtils.isShowMaxTime(itemBean.firsttime, itemBean?.lasttime);
    return Row(
      children: <Widget>[
        Container(
          alignment: Alignment.centerLeft,
          child: Text.rich(
            TextSpan(children: [
              TextSpan(
                  text:
                      "${VgDateTimeUtils.getFormatTimeStr(itemBean.firsttime) ?? "-"}"),
              TextSpan(text: isShowMax ? " 至 " : "", style: TextStyle()),
              TextSpan(
                  text: isShowMax
                      ? "${VgToolUtils.getHourAndMinuteStr(itemBean?.lasttime) ?? "-"}"
                      : ""),
            ]),
            style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
                fontFamily: "PingFang"),
          ),
        ),
        SizedBox(
          width: 14,
        ),
        Text(
          "${VgToolUtils.getDifferenceTimeStr(itemBean?.firsttime, itemBean?.lasttime) ?? ""}",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              fontFamily: "PingFang"),
        )
      ],
    );
  }

  ///今日刷脸数
  _todayFaceCnt(int faceCnt) {
     return Visibility(
      // visible: faceCnt > 0,
      visible: true,
      child: Row(
        children: <Widget>[
          Container(
            height: 12,
            width: 1,
            color: VgColors.INPUT_BG_COLOR,
            margin: EdgeInsets.symmetric(horizontal: 10),
          ),
          RichTextWidget(contentMap: LinkedHashMap.from({
            '今日刷脸':Color(0xff5e687c),
            '${faceCnt??0}':ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            '人':Color(0xff5e687c),
          }),)
        ],
      ),
    );
  }
}

class MySliverDelegate extends SliverPersistentHeaderDelegate {
  MySliverDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight; //最小高度
  final double maxHeight; //最大高度
  final Widget child; //子Widget布局

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => Math.max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override //是否需要重建
  bool shouldRebuild(MySliverDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
